package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.date.DateUtils;
import com.gitee.apanlh.util.date.format.DateTimeFormat;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.util.H5DomainUrlUtils;
import com.ts.api.http.platform.entity.apply.ApiPlatLeTianHuaApply;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatLeTianHuaDataExchange;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformMultiPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMaskConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 乐天花-全流程
 *
 * @author 李源聪
 */
@ApiPlan(productId = "219", type = ApiPlanConvertType.PLAT_PHONE_MASK)
public class ApiPlatLeTianHuaPhoneMaskConvert implements ApiPlatformPhoneMaskConvertHandler {
    private static final String KEY = "Dy7ZrIqb4BYJQgJD";
    private static final String CHANNEL_CODE = "681421960507461";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        ApiPlatLeTianHuaDataExchange apiPlatDataExchange = new ApiPlatLeTianHuaDataExchange();
        // 掩码手机号
        apiPlatDataExchange.setPhoneMask(apiDataExchangeParameter.getPhoneMask());
        // 用户名
        apiPlatDataExchange.setUserName("浩安星");
        // 用户ip
        apiPlatDataExchange.setIp(apiDataExchangeParameter.getIp());
        // 城市代码
        apiPlatDataExchange.setAreaCode(apiDataExchangeParameter.getAreaCode());
        // 城市
        apiPlatDataExchange.setCity(apiDataExchangeParameter.getCity());
        // 年龄
        apiPlatDataExchange.setAge(apiDataExchangeParameter.getAge());
        // 时间
        apiPlatDataExchange.setApplyTime(DateUtils.currentTime(DateTimeFormat.DATE_TIME_FULL));
        // 性别（0-女;1-男（默认））
        String sex = ChooseEq.create(apiDataExchangeParameter.getSex())
                .when("0", "1")
                .when("1", "0")
                .end("1");
        apiPlatDataExchange.setSex(sex);
        // 贷款金额(元)
        String loanAmount = ChooseEq.create(apiDataExchangeParameter.getLoanAmount())
                .when("1", "30000")
                .when("2", "50000")
                .when("3", "100000")
                .when("4", "200000")
                .end("30000");
        apiPlatDataExchange.setLoanAmount(loanAmount);
        // 信用情况：0未知  1-有逾期 ；2-无逾期
        String overdue = ChooseEq.create(apiDataExchangeParameter.getOverdue())
                .when("1", "2")
                .when("2", "1")
                .when("3", "1")
                .end("0");
        apiPlatDataExchange.setOverdue(overdue);
        // 学历：0-未知；1-初中及以下； 2-高中；3-大专； 4-本科；5 研究生及以上
        String educationAttainment = ChooseEq.create(apiDataExchangeParameter.getEducationAttainment())
                .when("1", "1")
                .when("2", "2")
                .when("3", "2")
                .when("4", "3")
                .when("5", "4")
                .when("6", "5")
                .end("0");
        apiPlatDataExchange.setEducationAttainment(educationAttainment);
        // 职业信息：1-自由职业者（默认）；  2-上班族； 3-(公务员/事业/国企) ；4-企业主； 5-个体户
        String career = ChooseEq.create(apiDataExchangeParameter.getCareer())
                .when("1", "2")
                .when("2", "1")
                .when("3", "4")
                .when("4", "3")
                .when("5", "5")
                .end("1");
        apiPlatDataExchange.setCareer(career);
        // 最低月收入(单位：元）
        String monthlySalary = ChooseEq.create(apiDataExchangeParameter.getMonthlySalary())
                .when("1", "1000")
                .when("2", "3000")
                .when("3", "8000")
                .when("4", "150000")
                .when("5", "300000")
                .end("1000");
        apiPlatDataExchange.setMonthlySalary(monthlySalary);
        // 工资发放形式(0无 1 银行卡 2 现金 3 银行转账 4 微信、支付宝）
        String salaryPayMethod = ChooseEq.create(apiDataExchangeParameter.getSalaryPayMethod())
                .when("1", "1")
                .when("2", "2")
                .when("3", "2")
                .end("0");
        apiPlatDataExchange.setSalaryPayMethod(salaryPayMethod);
        // 工龄(上班族、公务员/事业/国企)  0-无 1-(0-6个月) 2-(6-12个月)  3-(12个月以上)
        String yearsService = ChooseEq.create(apiDataExchangeParameter.getYearsService())
                .when("1", "1")
                .when("2", "2")
                .when("3", "3")
                .end("0");
        apiPlatDataExchange.setYearsService(yearsService);
        // 经营流水（具体限制金额-分）（企业主、个体户）
        String bizBankDetails = ChooseEq.create(apiDataExchangeParameter.getBizBankDetails())
                .when("1", "100000")
                .when("2", "500000")
                .when("3", "1000000")
                .end("100000");
        apiPlatDataExchange.setBizBankDetails(bizBankDetails);
        // 营业执照（0-无  1-两年以下 2-两年以上）
        String bizLicenseYear = ChooseEq.create(apiDataExchangeParameter.getBizLicenseYear())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "2")
                .end("0");
        apiPlatDataExchange.setBizLicenseYear(bizLicenseYear);
        // 社保（0-无；1-6个月以下； 2-6个月及以上）
        String socialSecurity = ChooseEq.create(apiDataExchangeParameter.getSocialSecurity())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "1")
                .end("0");
        apiPlatDataExchange.setSocialSecurity(socialSecurity);
        // 公积金（ 0-无； 1-.未满6个月 ；2-6个月及以上）
        String providentFund = ChooseEq.create(apiDataExchangeParameter.getProvidentFund())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "1")
                .end("0");
        apiPlatDataExchange.setProvidentFund(providentFund);
        // 房产信息（0-无；1-按揭房产；2-全款房产）
        String realEstateInfo = ChooseEq.create(apiDataExchangeParameter.getRealEstateInfo())
                .when("1", "0")
                .when("2", "2")
                .when("3", "2")
                .when("4", "2")
                .when("5", "1")
                .when("6", "2")
                .end("0");
        apiPlatDataExchange.setRealEstateInfo(realEstateInfo);
        // 车产信息（0-无；1-按揭车；2-全款车）
        String carInfo = ChooseEq.create(apiDataExchangeParameter.getCarInfo())
                .when("1", "0")
                .when("2", "2")
                .when("3", "2")
                .when("4", "2")
                .end("0");
        apiPlatDataExchange.setCarInfo(carInfo);
        // 保险保单（0-无；1-1年以内；2-1年以上
        String insurancePolicy = ChooseEq.create(apiDataExchangeParameter.getInsurancePolicy())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "1")
                .end("0");
        apiPlatDataExchange.setInsurancePolicy(insurancePolicy);
        // 信用卡（0-无；1-2万元以内；2-2万元以上
        String creditLimit = ChooseEq.create(apiDataExchangeParameter.getCreditLimit())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .when("5", "2")
                .when("6", "1")
                .end("0");
        apiPlatDataExchange.setCreditLimit(creditLimit);
        // 芝麻分（0-未知；1-550分以下； 2-550~599； 3-600~649；4-650~699； 5-700分以上）
        String sesameCredit = ChooseEq.create(apiDataExchangeParameter.getSesameCredit())
                .when("1", "2")
                .when("2", "3")
                .when("3", "4")
                .when("4", "5")
                .end("2");
        apiPlatDataExchange.setSesameCredit(sesameCredit);
        // 花呗（0-无；1-有）
        String hbLimit = ChooseEq.create(apiDataExchangeParameter.getHbLimit())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .when("5", "1")
                .end("0");
        apiPlatDataExchange.setHbLimit(hbLimit);
        // 京东白条（0-无；1-有）
        String btLimit = ChooseEq.create(apiDataExchangeParameter.getBtLimit())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .when("5", "1")
                .end("0");
        apiPlatDataExchange.setBtLimit(btLimit);
        // 贷款期限（月）
        String termNum = ChooseEq.create(apiDataExchangeParameter.getLoanTerm())
                .when("1", "3")
                .when("2", "6")
                .when("3", "12")
                .when("4", "24")
                .when("5", "36")
                .when("6", "60")
                .end("3");
        apiPlatDataExchange.setTermNum(termNum);
        // 贷款用途（0-其他； 1-购房；2-结婚； 3-消费； 4-教育培训；5-购车；6-装修；
        String loanPurpose = ChooseEq.create(apiDataExchangeParameter.getLoanPurpose())
                .when("1", "3")
                .when("2", "4")
                .when("3", "2")
                .when("4", "6")
                .when("5", "0")
                .when("6", "3")
                .end("0");
        apiPlatDataExchange.setLoanPurpose(loanPurpose);
        // 客户类型
        apiPlatDataExchange.setClientType("0");
        AES aes = AES.createEcb(KEY.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(apiPlatDataExchange));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", CHANNEL_CODE);
            newMap.put("content", data);
        });
        return JsonUtils.toJson(map);
    }


    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        ApiPlatLeTianHuaApply apiPlatApply = new ApiPlatLeTianHuaApply();
        // 撞库返回id
        apiPlatApply.setOrderId(apiApplyParameter.getApplyId());
        // 手机号明文
        apiPlatApply.setPhone(apiApplyParameter.getPhone());
        // 用户名
        apiPlatApply.setUserName(apiApplyParameter.getUserName());
        // ip
        apiPlatApply.setIp(apiApplyParameter.getIp());
        // 城市编码
        apiPlatApply.setAreaCode(apiApplyParameter.getAreaCode());
        // 城市
        apiPlatApply.setCity(apiApplyParameter.getCity());
        // 年龄
        apiPlatApply.setAge(apiApplyParameter.getAge());
        // 时间
        apiPlatApply.setApplyTime(DateUtils.currentTime(DateTimeFormat.DATE_TIME_FULL));
        // 性别（0-女;1-男（默认））
        String sex = ChooseEq.create(apiApplyParameter.getSex())
                .when("0", "1")
                .when("1", "0")
                .end("1");
        apiPlatApply.setSex(sex);
        // 贷款金额(元)
        String loanAmount = ChooseEq.create(apiApplyParameter.getLoanAmount())
                .when("1", "30000")
                .when("2", "50000")
                .when("3", "100000")
                .when("4", "200000")
                .end("30000");
        apiPlatApply.setLoanAmount(loanAmount);
        // 信用情况：0未知  1-有逾期 ；2-无逾期
        String overdue = ChooseEq.create(apiApplyParameter.getOverdue())
                .when("1", "2")
                .when("2", "1")
                .when("3", "1")
                .end("0");
        apiPlatApply.setOverdue(overdue);
        // 学历：0-未知；1-初中及以下； 2-高中；3-大专； 4-本科；5 研究生及以上
        String educationAttainment = ChooseEq.create(apiApplyParameter.getEducationAttainment())
                .when("1", "1")
                .when("2", "2")
                .when("3", "2")
                .when("4", "3")
                .when("5", "4")
                .when("6", "5")
                .end("0");
        apiPlatApply.setEducationAttainment(educationAttainment);
        // 职业信息：1-自由职业者（默认）；  2-上班族； 3-(公务员/事业/国企) ；4-企业主； 5-个体户
        String career = ChooseEq.create(apiApplyParameter.getCareer())
                .when("1", "2")
                .when("2", "1")
                .when("3", "4")
                .when("4", "3")
                .when("5", "5")
                .end("1");
        apiPlatApply.setCareer(career);
        // 最低月收入(单位：元）
        String monthlySalary = ChooseEq.create(apiApplyParameter.getMonthlySalary())
                .when("1", "1000")
                .when("2", "3000")
                .when("3", "8000")
                .when("4", "150000")
                .when("5", "300000")
                .end("1000");
        apiPlatApply.setMonthlySalary(monthlySalary);
        // 工资发放形式(0 无 1 银行卡 2 现金 3 银行转账 4 微信、支付宝）
        String salaryPayMethod = ChooseEq.create(apiApplyParameter.getSalaryPayMethod())
                .when("1", "1")
                .when("2", "2")
                .when("3", "2")
                .end("0");
        apiPlatApply.setSalaryPayMethod(salaryPayMethod);
        // 工龄(上班族、公务员/事业/国企)  0-无 1-(0-6个月) 2-(6-12个月)  3-(12个月以上)
        String yearsService = ChooseEq.create(apiApplyParameter.getYearsService())
                .when("1", "1")
                .when("2", "2")
                .when("3", "3")
                .end("0");
        apiPlatApply.setYearsService(yearsService);
        // 经营流水（具体限制金额-分）（企业主、个体户）
        String bizBankDetails = ChooseEq.create(apiApplyParameter.getBizBankDetails())
                .when("1", "100000")
                .when("2", "500000")
                .when("3", "1000000")
                .end("100000");
        apiPlatApply.setBizBankDetails(bizBankDetails);
        // 营业执照（0-无  1-两年以下 2-两年以上）
        String bizLicenseYear = ChooseEq.create(apiApplyParameter.getBizLicenseYear())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "2")
                .end("0");
        apiPlatApply.setBizLicenseYear(bizLicenseYear);
        // 社保（0-无；1-6个月以下； 2-6个月及以上）
        String socialSecurity = ChooseEq.create(apiApplyParameter.getSocialSecurity())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "1")
                .end("0");
        apiPlatApply.setSocialSecurity(socialSecurity);
        // 公积金（ 0-无； 1-.未满6个月 ；2-6个月及以上）
        String providentFund = ChooseEq.create(apiApplyParameter.getProvidentFund())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "1")
                .end("0");
        apiPlatApply.setProvidentFund(providentFund);
        // 房产信息（0-无；1-按揭房产；2-全款房产）
        String realEstateInfo = ChooseEq.create(apiApplyParameter.getRealEstateInfo())
                .when("1", "0")
                .when("2", "2")
                .when("3", "2")
                .when("4", "2")
                .when("5", "1")
                .when("6", "2")
                .end();
        apiPlatApply.setRealEstateInfo(realEstateInfo);
        // 车产信息（0-无；1-按揭车；2-全款车）
        String carInfo = ChooseEq.create(apiApplyParameter.getCarInfo())
                .when("1", "0")
                .when("2", "2")
                .when("3", "2")
                .when("4", "2")
                .end("0");
        apiPlatApply.setCarInfo(carInfo);
        // 保险保单（0-无；1-1年以内；2-1年以上
        String insurancePolicy = ChooseEq.create(apiApplyParameter.getInsurancePolicy())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "1")
                .end("0");
        apiPlatApply.setInsurancePolicy(insurancePolicy);
        // 信用卡（0-无；1-2万元以内；2-2万元以上
        String creditLimit = ChooseEq.create(apiApplyParameter.getCreditLimit())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .when("5", "2")
                .when("6", "1")
                .end("0");
        apiPlatApply.setCreditLimit(creditLimit);
        // 芝麻分（0-未知；1-550分以下； 2-550~599； 3-600~649；4-650~699； 5-700分以上）
        String sesameCredit = ChooseEq.create(apiApplyParameter.getSesameCredit())
                .when("1", "2")
                .when("2", "3")
                .when("3", "4")
                .when("4", "5")
                .end("0");
        apiPlatApply.setSesameCredit(sesameCredit);
        // 花呗（0-无；1-有）
        String hbLimit = ChooseEq.create(apiApplyParameter.getHbLimit())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .when("5", "1")
                .end("0");
        apiPlatApply.setHbLimit(hbLimit);
        // 京东白条（0-无；1-有）
        String btLimit = ChooseEq.create(apiApplyParameter.getBtLimit())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .when("5", "1")
                .end("0");
        apiPlatApply.setBtLimit(btLimit);
        // 贷款期限（月）
        String termNum = ChooseEq.create(apiApplyParameter.getLoanTerm())
                .when("1", "3")
                .when("2", "6")
                .when("3", "12")
                .when("4", "24")
                .when("5", "36")
                .when("6", "60")
                .end("3");
        apiPlatApply.setTermNum(termNum);
        // 贷款用途（0-其他； 1-购房；2-结婚； 3-消费； 4-教育培训；5-购车；6-装修；
        String loanPurpose = ChooseEq.create(apiApplyParameter.getLoanPurpose())
                .when("1", "3")
                .when("2", "4")
                .when("3", "2")
                .when("4", "6")
                .when("5", "0")
                .when("6", "3")
                .end("0");
        apiPlatApply.setLoanPurpose(loanPurpose);
        // 客户类型
        apiPlatApply.setClientType("0");
        // 列表
        apiPlatApply.setAuthList(CollUtils.newArrayList(newList -> {
            ApiPlatLeTianHuaApply.AuthList authList = new ApiPlatLeTianHuaApply.AuthList();
            authList.setAuthName("个人信息授权协议");
            authList.setAuthUrl(H5DomainUrlUtils.createUserProtocolUrl(apiApplyParameter.getProductPlanId(), apiApplyParameter.getPhoneMd5()));
            newList.add(authList);
        }));
        apiPlatApply.setSourceId("安心分期");
        // 加密
        AES aes = AES.createEcb(KEY.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(apiPlatApply));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", CHANNEL_CODE);
            newMap.put("content", data);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMaskApply respApply(String respJson) throws Exception {
        //  进件返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        return RespPlatformPhoneMaskApply.ofSuc();
    }

    @Override
    public RespPlatformMultiPhoneMaskDataExchange respDataExchange(String respJson) {
        //  撞库返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }

        JSONObject resData = JsonUtils.get(respJson).getJSONObject("data");
        if (ValidParam.isEmpty(resData)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }

        RespPlatformMultiPhoneMaskDataExchange respPlatformMultiPhoneMaskDataExchange = RespPlatformMultiPhoneMaskDataExchange.ofSuc();
        List<RespPlatformPhoneMaskDataExchange> listRespPlatformPhoneMaskDataExchange = CollUtils.newArrayList();
        if (ValidParam.isNotNull(resData)) {
            BigDecimal price = resData.getBigDecimal("sysSellMoney");
            String companyName = resData.getString("companyName");
            String productName = resData.getString("productName");
            String logo = resData.getString("logoUrl");
            String orderId = resData.getString("orderId");

            List<ApiProtocol> protocolList = CollUtils.newArrayList(newList -> {
                //  获取协议
                JSONArray listProtocolResult = resData.getJSONArray("authList");
                IteratorUtils.array(listProtocolResult, (protocolResult, index) -> {
                    JSONObject protocolObject = listProtocolResult.getJSONObject(index);
                    ApiProtocol protocol = new ApiProtocol();
                    protocol.setProtocolName(protocolObject.getString("authName"));
                    protocol.setProtocolUrl(protocolObject.getString("authUrl"));
                    newList.add(protocol);
                });
            });

            List<String> phoneMd5List = CollUtils.newArrayList(newList -> {
                JSONArray jsonArray = resData.getJSONArray("phoneMd5List");
                IteratorUtils.array(jsonArray, (protocolResult, index) -> {
                    String phoneMd5 = jsonArray.getString(index);
                    newList.add(phoneMd5);
                });
            });
            RespPlatformPhoneMaskDataExchange result = RespPlatformPhoneMaskDataExchange.of();

            result.setPrice(price);
            result.setLogoPath(logo);
            result.setDisplayName(companyName);
            result.setProductName(productName);
            result.setApplyId(orderId);
            result.setProtocolList(protocolList);
            result.setListPhoneMd5(phoneMd5List);
            listRespPlatformPhoneMaskDataExchange.add(result);
        }
        respPlatformMultiPhoneMaskDataExchange.setListPhoneMask(listRespPlatformPhoneMaskDataExchange);
        return respPlatformMultiPhoneMaskDataExchange;
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return null;
    }
}
